package edu.xlh.travel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import edu.xlh.travel.common.Result;
import edu.xlh.travel.dao.SysLogDao;
import edu.xlh.travel.pojo.*;
import edu.xlh.travel.service.SysLogService;
import edu.xlh.travel.util.DateTimeUtil;
import edu.xlh.travel.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service
@Transactional
public class SysLogServiceImpl implements SysLogService {
    @Autowired
    private SysLogDao sysLogDao;
    @Override
    public void save(SysLog sysLog) {
        sysLogDao.save(sysLog);
    }

    @Override
    public Result findAllSysLogInfo(int page, int limit ,HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201);
        }
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> sysLogList = new ArrayList<>();
                sysLogList.add(criteriaBuilder.equal(root.get("delFlag"), "0"));
                return criteriaBuilder.and(sysLogList.toArray(new Predicate[sysLogList.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable= PageRequest.of(page-1,limit ,sort);
        Page<SysLog> sysLogPage = sysLogDao.findAll(specification , pageable);
        if (sysLogPage!=null) {
            return new Result(0 , "系统日志分页数据获取成功" , new PageResult<SysLog>(sysLogPage.getTotalElements(), sysLogPage.getContent()));
        }
        return new Result(201, "系统日志分页数据获取失败");
    }

    @Override
    public Result QuerySysLogByCondition(Integer page, Integer limit , SysLog sysLog, HttpSession session) {
        User userFromSession = (User)session.getAttribute("admin");
        if (userFromSession == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> sysLogList = new ArrayList<>();
                if (!StringUtils.isEmpty( sysLog.getUserName())) {
                    sysLogList.add(criteriaBuilder.like(root.get("userName") , "%" + sysLog.getUserName() + "%"));
                }
                if (!StringUtils.isEmpty( sysLog.getOperation())) {
                    sysLogList.add(criteriaBuilder.like(root.get("operation") , "%" + sysLog.getOperation() + "%"));
                }
                if (!StringUtils.isEmpty( sysLog.getMethod())) {
                    sysLogList.add(criteriaBuilder.like(root.get("method") , "%" + sysLog.getMethod() + "%"));
                }
                if (!StringUtils.isEmpty( sysLog.getTime())) {
                    sysLogList.add(criteriaBuilder.between(root.get("time") , String.valueOf(Integer.valueOf(sysLog.getTime()) - 1) , String.valueOf(Integer.valueOf(sysLog.getTime()) + 1)));
                }
                if (sysLog.getCreateTime() != null) {
                    String crateTime = DateTimeUtil.dateToStr(sysLog.getCreateTime(), "yyyy-MM-dd");
                    String crateTimeStartTimeToStr = crateTime + " " + "00:00:00";
                    String crateTimeEndTimeToStr = crateTime + " " + "23:59:59";
                    Date crateTimeStartTimeToDate = DateTimeUtil.strToDate(crateTimeStartTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    Date crateTimeEndTimeToDate = DateTimeUtil.strToDate(crateTimeEndTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    sysLogList.add(criteriaBuilder.between(root.get("createTime") ,  crateTimeStartTimeToDate , crateTimeEndTimeToDate));
                }
                return criteriaBuilder.and(sysLogList.toArray(new Predicate[sysLogList.size()]));
            }
        };
        Pageable pageable= PageRequest.of(page-1,limit);
        Page<SysLog> sysLogListPage  = sysLogDao.findAll(specification , pageable);
        if (sysLogListPage!=null) {
            return new Result(0 , "系统日志分页数据获取成功" , new PageResult<SysLog>(sysLogListPage.getTotalElements(), sysLogListPage.getContent()));
        }
        return new Result(201 , "返回系统日志列表失败");
    }

    @Override
    public Result batchDelete(JSONArray jsonArray, HttpSession session) {
        List<SysLog> sysLogList = JSON.parseArray(jsonArray.toJSONString() , SysLog.class);
        try {
            sysLogList.stream().iterator().forEachRemaining(sysLog -> {
                sysLogDao.updateSysLogDelFlagBySysLogId(sysLog.getId() , "1");
            });
        }catch (Exception e) {
            return new Result(201);
        }
        return new Result(200);
    }

    @Override
    public Result deleteById(String id, HashMap hashMap, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        String sysLogId = (String) hashMap.get("id");
        if (id.equals(sysLogId)) {
            try {
                sysLogDao.updateSysLogDelFlagBySysLogId(sysLogId , "1");
            } catch (Exception e) {
                return new Result(201 , "id为"+sysLogId+"的日志监控记录"+"删除失败");
            }
        } else {
            return new Result(202 , "id为"+sysLogId+"的日志监控id有问题");
        }
        return new Result(200 , "id为"+sysLogId+"的日志监控记录"+"删除成功");
    }
}
